import { getModule, Module, Mutation, VuexModule } from 'vuex-module-decorators';
import store from '@/store/index';

const syncStorage = (data: any) => {
    localStorage.setItem('quick', JSON.stringify(data));
}

const getStorage = () => {
    try {
        let data = JSON.parse(localStorage.getItem('quick') as string);
        if (data) {
            return data;
        }
        return [];
    } catch (e) {
        return [];
    }
}

@Module({ name: 'quick', dynamic: true, namespaced: true, store })
export default class QuickStore extends VuexModule {
    private $list: any[] = [];

    public get list(): any[] {
        return this.$list;
    }

    @Mutation
    init() {
        this.$list = getStorage();
    }

    /**
     * 添加快捷按钮
     * @param text
     * @param route
     */
    @Mutation
    addBtn({ text, route }: { text: string, route: string }) {
        const idx = this.$list.findIndex(_ => _.route === route);
        if (idx === -1) {
            this.$list.push({
                text,
                route,
            });
            syncStorage(this.$list);
        }
    }

    /**
     * 删除快捷按钮
     * @param route
     */
    @Mutation
    delBtn(route: string) {
        const idx = this.$list.findIndex(_ => _.route === route);

        if (idx > -1) {
            this.$list.splice(idx, 1);
        }
        syncStorage(this.$list);
    }
}

export const QuickModule = getModule(QuickStore);
